<template>
  <teleport to="#cutdownContainer">
    <h3 v-if="countDownVisible">自动刷新倒计时：剩余{{ countDown }}秒</h3>
  </teleport>
  <div ref="trendCanvas" class="trendCanvas"></div>
</template>
<script setup>
  import * as echarts from 'echarts';

  import { useRoute } from 'vue-router';
  import { ref, watch, watchEffect, inject, onMounted, onActivated, onDeactivated, onUnmounted } from 'vue';

  import refresher from '@/libs/autoRefreshShares';

  const $route = useRoute();
  const $http = inject('$http');

  const props = defineProps({
    code: {
      type: String
    },
    contentWidth: {
      type: Number
    },
    contentHeight: {
      type: Number
    }
  });

  const trendCanvas = ref();
  const chartTitle = ref('');

  const countDownNumber = 5;
  const countDown = ref(countDownNumber);
  const countDownVisible = ref(false);

  let echartsInstance = null;
  const echartsOption = {
    title: {
      text: `走势图 - ${chartTitle.value}`
    },
    grid: {
      left: '30px',
      right: '20px',
      bottom: '10px',
      top: '65px',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        animation: true
      },
      formatter: function (params) {
        let result = `${params[0].name}<br />`;

        params.forEach(item => {
          let unit = item.seriesName == '涨幅' ? '%' : '元';

          result += `<p class="chart-tooltip-line"><b>${item.marker}${item.seriesName}</b> <b>${item.value} ${unit}</b></p>`;
        });

        return result;
      }
    },
    legend: {
      data: ['当前价', '涨幅']
    },
    toolbox: {
      show: true,
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        dataView: { readOnly: false },
        magicType: { type: ['line', 'bar'] },
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        formatter: '{value}'
      },
      axisPointer: {
        show: true,
        label: {
          show: true,
          formatter: '{value}'
        }
      },
      data: []
    },
    yAxis: [
      {
        type: 'value',
        name: '当前价(元)',
        min: 0,
        position: 'left',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '涨幅(%)',
        min: -20,
        max: 20,
        position: 'right',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '当前价',
        type: 'line',
        smooth: true,
        yAxisIndex: 0,
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [{ type: 'average', name: '平均值' }]
        }
      },
      {
        name: '涨幅',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [{ type: 'average', name: '平均值' }]
        },
        itemStyle: {
          color: function (params) {
            if (params.value > 0) {
              return '#C1232B';
            } else {
              return 'green';
            }
          }
        }
      }
    ],
    visualMap: {
      show: false,
      // 只对第二条线进行设置
      seriesIndex: 1,
      textStyle: {
        color: '#000'
      },
      pieces: [
        { min: 0, max: 2000000, label: '涨', color: '#C1232B' },
        { min: -20000, max: 0, label: '跌', color: 'green' }
      ],
      outOfRange: {
        color: 'green'
      }
    }
  };

  async function RenderMetric() {
    if (!echartsInstance) {
      echartsInstance = echarts.init(trendCanvas.value);

      // 使用刚指定的配置项和数据显示图表。
      echartsInstance.setOption(echartsOption);
    }

    let rs = await $http.get(`/api/shares/${props.code}/statistics`);

    const d = rs.datas;
    let latestPrice = '';

    if (rs.datas && rs.datas.length > 0) {
      chartTitle.value = rs.datas[0].Name || $route.query.title;

      let current = rs.datas[rs.datas.length - 1];

      latestPrice = ` / ${(current.CurrentPrice || 0).toFixed(2)}元 / ${(((current.CurrentPrice - current.YesterdayPrice) / current.YesterdayPrice) * 100).toFixed(2)}%`;
    }

    echartsOption.xAxis.data = d.map(function (m) {
      return `${m.Date} ${m.Time}`;
    });

    echartsOption.title.text = `走势图 - ${chartTitle.value}${latestPrice}`;
    echartsOption.series[0].data = d.map(function (m) {
      return m.CurrentPrice.toFixed(2);
    });

    echartsOption.series[1].data = d.map(function (m) {
      return (((m.CurrentPrice - m.YesterdayPrice) / m.YesterdayPrice) * 100).toFixed(2);
    });

    if (echartsInstance) {
      // 使用刚指定的配置项和数据显示图表。
      echartsInstance.setOption(echartsOption);
      echartsInstance.resize();
    }

    // 显示tooltip
    echartsInstance.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: 0
    });
  }

  function ResizeChartPanel() {
    let canvas = trendCanvas.value;

    if (canvas) {
      canvas.style.height = props.contentHeight + 'px';
    }

    if (echartsInstance) {
      canvas.style.width = `${props.contentWidth}px`;

      echartsInstance.resize();
    }
  }

  watch($route, () => {
    props.code = $route.params.code;
    chartTitle.value = $route.query.title;
  });

  watchEffect(() => {
    ResizeChartPanel();
  });

  onActivated(() => {
    RenderMetric();
  });

  onMounted(() => {
    chartTitle.value = $route.query.title;

    RenderMetric();

    refresher.start({
      step({ visible, number }) {
        countDown.value = number;
        countDownVisible.value = visible;
      },
      done() {
        RenderMetric();
      }
    });
  });

  onUnmounted(() => {
    refresher.stop();

    echartsInstance = null;
  });
</script>
